<template>
  <div>
    <el-form class="query-form" :inline="true">
      <el-form-item v-if="showBack">
        <el-button type="primary" @click="$router.back()">返回</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fixed()">实地走访</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="power()">用电查询</el-button>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary"
                   @click="abnorma()"
                   v-show="isRiskPerson">异常登记</el-button>
      </el-form-item> -->
      <el-form-item v-show="isRiskPerson || isGov || isCredit">
        <el-button type="primary" @click="showAbnorma()">管理登记</el-button>
      </el-form-item>
      <el-form-item v-show="isRiskPerson && !isGov">
        <el-button type="primary" @click="showRepayList()">还款跟踪</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="gocontrol()">监控查看</el-button>
      </el-form-item>
      <el-form-item v-show="isBank">
        <el-button type="primary" @click="manageVisible = true">贷后管理</el-button>
      </el-form-item>
      <!--<el-form-item v-show="!isGov">-->
      <!--<el-button type="primary"-->
      <!--@click="gofinance()">财务查看</el-button>-->
      <!--</el-form-item>-->
      <!--<el-form-item v-show="!isGov">-->
      <!--<el-button type="primary"-->
      <!--@click="gofarm(monitorData[0].customer_id)">农场动态查看</el-button>-->
      <!--</el-form-item>-->
    </el-form>

    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column label="时间" align="center" min-width="20">
          <template slot-scope="scope">
            {{ $utils.dateFormat(scope.row.visit_date, 'yyyy.MM.dd') }}
          </template>
        </el-table-column>
        <el-table-column
          label="用户名"
          align="center"
          prop="visit_person"
          min-width="30"
        ></el-table-column>
        <el-table-column label="记录" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.visit_status === '1'">{{ scope.row.visit_des }}</span>
            <span v-else-if="scope.row.visit_status === '0'" style="color: red">
              {{ scope.row.visit_des }}
            </span>
            <span v-else style="color: red">{{ scope.row.visit_des }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="isRiskPerson" align="center">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="bottom">
              <el-button type="text" class="text-success px-3 m-x3" @click="editData(scope.row)">
                <i class="fa fa-edit"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="bottom">
              <el-button type="text" class="text-danger px-3 m-x3" @click="deleteData(scope.row)">
                <i class="fa fa-trash"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <el-dialog
      top="80px"
      width="600px"
      append-to-body
      :visible.sync="editRecordVisible"
      :before-close="hanldRecordClose"
      :close-on-click-modal="false"
    >
      <h5 class="text-center mb-3">监管登记</h5>
      <el-input
        type="textarea"
        class="mb-3"
        v-model="recordData.visit_des"
        :autosize="{ minRows: 4, maxRows: 100 }"
        placeholder="走访记录"
      ></el-input>
      <div class="d-flex mb-3">
        <div class="dl-dt mt-2">走访时间：</div>
        <el-date-picker
          v-model="recordData.visit_date"
          @change="setTime"
          placeholder="走访时间"
          type="date"
          value-format="yyyy-MM-dd"
          :clearable="true"
        ></el-date-picker>
      </div>

      <div class="visit-fuj" style="text-align: center">
        <el-button @click="hanldRecordClose">取消</el-button>
        <el-button
          type="primary"
          @click="updateRecord('credit', recordData, 'credit_visit_record')"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
    <visit-history :visible.sync="editVisible" @success="gettableflData"></visit-history>
    <ele-history :visible.sync="powerVisible" @success="gettableflData"></ele-history>
    <el-dialog
      width="70%"
      top="80px"
      append-to-body
      :visible.sync="abnormaVisible"
      :before-close="abnormaClose"
      :close-on-click-modal="false"
    >
      <h5 align="center">异常登记</h5>
      <div class="card">
        <div class="card-body">
          <div class="dl-wrap">
            <div class="dl-dt">异常类选择：</div>
            <div class="dl-dd">
              <el-select v-model="visit_type" @change="setType">
                <el-option value="逾期异常" label="逾期异常" key="1"></el-option>
                <el-option value="经营异常" label="经营异常" key="2"></el-option>
                <el-option value="资金使用异常" label="资金使用异常" key="3"></el-option>
                <el-option value="其它" label="其它" key="4"></el-option>
              </el-select>
            </div>
          </div>
          <div class="dl-wrap" v-if="visit_type === '逾期异常'">
            <div class="dl-dt">逾期时间：</div>
            <div class="dl-dd">
              <el-date-picker
                v-model="date"
                @change="setTime"
                placeholder="逾期时间"
                type="date"
                value-format="yyyy-MM-dd"
                :clearable="true"
              ></el-date-picker>
            </div>
          </div>
          <div class="dl-wrap" v-if="visit_type === '逾期异常'">
            <div class="dl-dt">逾期时长：</div>
            <div class="dl-dd">
              <el-input
                v-model="time"
                placeholder="逾期时长"
                @blur="setTime"
                style="width: 220px"
              ></el-input>
              天
            </div>
          </div>
          <div class="dl-wrap" v-if="visit_type === '逾期异常'">
            <div class="dl-dt">逾期金额(元)：</div>
            <div class="dl-dd">
              <el-input
                v-model="money"
                placeholder="逾期金额"
                @blur="setTime"
                style="width: 220px"
              ></el-input>
              元
            </div>
          </div>
          <div class="dl-wrap">
            <div class="dl-dt">补充说明：</div>
            <div class="dl-dd">
              <el-input
                type="textarea"
                v-model="abaData.visit_des"
                :autosize="{ minRows: 4, maxRows: 100 }"
              ></el-input>
            </div>
          </div>
        </div>
      </div>
      <div class="visit-fuj" style="text-align: center">
        <el-button @click="abnormaClose">取消</el-button>
        <el-button type="primary" @click="submitnorma('credit', abaData, 'credit_visit_record')">
          保存
        </el-button>
        <!--<el-button style="margin-left: 50px" @click="submitabnorma">保存</el-button>-->
      </div>
    </el-dialog>
    <video-list :visible.sync="controlVisible"></video-list>
    <after-manage-bank :visible.sync="manageVisible" @success="gettableflData"></after-manage-bank>

    <after-ab-editor-gov
      v-if="isGov"
      :visible.sync="abEditorVisible"
      @success="gettableflData"
    ></after-ab-editor-gov>

    <after-ab-editor-credit
      v-else-if="isCredit"
      :visible.sync="abEditorVisible"
      @success="gettableflData"
    ></after-ab-editor-credit>

    <after-ab-editor
      v-else
      :visible.sync="abEditorVisible"
      @success="gettableflData"
    ></after-ab-editor>

    <after-repay-editor
      :visible.sync="repayEditorVisble"
      @success="gettableflData"
    ></after-repay-editor>
  </div>
</template>
<script>
import AfterAbEditor from './AfterAbEditor'
import AfterAbEditorGov from './AfterAbEditorGov'
import AfterAbEditorCredit from './AfterAbEditorCredit'
import AfterRepayEditor from './AfterRepayEditorDialog'
import VisitHistory from './VisitHistory'
import EleHistory from './EleHistory'
import VideoList from './VideoList'
import AfterManageBank from './AfterManageBank'
import { enumVisUseType, enumDynamicType, enumVisitType, enumVType } from '@/credit/plugins/enum'
import { echartsXFormatter } from '@vimi/utils-tool'
const visdate = new Date().toLocaleDateString()
export default {
  components: {
    AfterAbEditor,
    AfterAbEditorGov,
    AfterRepayEditor,
    AfterAbEditorCredit,
    VisitHistory,
    EleHistory,
    VideoList,
    AfterManageBank,
  },
  props: {
    queryId: String,
    imgType: Boolean,
    showBack: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      enumVisUseType,
      enumDynamicType,
      enumVisitType,
      enumVType,
      errorState: [],
      visdate,
      recordId: '',
      editRecordVisible: false,
      recordData: {},
      eleData: [],
      option: null,
      fixedData: [{}],
      fixData: [{}],
      manageVisible: false,
      flowName: 'credit_visit_record',
      flowId: '',
      fixedVisible: false,
      flowData: [{}],
      floweditData: {},
      abnormaVisible: false,
      visit_type: '',
      date: '',
      time: '',
      money: '',
      abData: [{}],
      tablefeilData: [],
      abnormaData: {},
      relatedData: {},
      editVisible: false,
      powerVisible: false,
      PowerinformationData: [{}],
      PowerData: [],
      showtype: '',
      selectEleNo: [],
      echartsImg: '',
      Page: 0,
      financeVisible: false,
      financeData: {},
      controlVisible: false,
      controlData: {},
      monitorData: [],
      farmVisible: false,
      PostEle: {},
      feilData: {},
      abaData: { visit_des: '' },
      feildData: {},
      multipleSelection: [],
      addData: [],
      name: '',
      userId: '',
      phoneNumber: '',
      realName: '',
      cateList: [],
      tableData: [{}],
      params: {
        'customer_id.eq': '',
      },
      liveVideo: [],
      Id: '',

      // 管理登记
      abEditorVisible: false,
      // 还款记录
      repayEditorVisble: false,
    }
  },
  computed: {
    user() {
      return this.$store.getters.user
    },
    org() {
      return this.$store.getters.org
    },
    job() {
      return this.user.job
    },
    isRiskPerson() {
      return ['org_corp', 'org_r_emp', 'org_r_manage', 'org_c_manage', 'org_credit_super'].includes(
        this.job
      )
    },
    isGov() {
      return this.org.orgClass && this.org.orgClass.indexOf('org_gov') > -1
    },
    isCredit() {
      return this.org.orgClass && this.org.orgClass.indexOf('org_credit') > -1
    },
    isBank() {
      return this.org.orgClass && this.org.orgClass.indexOf('org_bank') > -1
    },
  },
  watch: {
    value(val) {
      this.selected = val
    },
    queryId() {
      this.getData()
    },
  },
  created() {
    this.realName = this.user.realName
    this.name = this.user.userName
    this.phoneNumber = this.user.phoneNumber
    this.userId = this.user.userId
    this.id = this.queryId || this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.getData()
  },
  mounted() {},
  methods: {
    onInit(chart, index) {
      this.eleData[index].chart = chart
    },
    getData() {
      this.getflowData()
      this.getRelatedData()
      // this.getEleData()
      this.getfinanceData()
      // this.getmonitData()
      this.gettableflData()
      // this.powerData()
    },
    async powerData() {
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_ele_table', {
          'customer_related_id.eq': this.id,
        })
      )

      if (res && res.data) {
        this.eleData = res.data.map(item => {
          item.eleFee = []
          item.option = null
          item.imgData = ''
          item.chart = null
          return item
        })
        for (const d of this.eleData) {
          // this.$http.get(`/api/credit/datum_customer_ele_fee?groupFunc=${encodeURIComponent(`sum(datum_customer_ele_fee.ele_fee),
          // ROUND((SUM(datum_customer_ele_fee.ele_fee)-SUM(datum_customer_ele_fee.ele_fee/(1+datum_customer_ele_fee.fee_compare)))/
          // SUM(datum_customer_ele_fee.ele_fee/(1+datum_customer_ele_fee.fee_compare))|2),sum(datum_customer_ele_fee.ele_amount),
          // ROUND((SUM(datum_customer_ele_fee.ele_amount)-SUM(datum_customer_ele_fee.ele_amount/(1+datum_customer_ele_fee.fee_compare)))
          // /SUM(datum_customer_ele_fee.ele_amount/(1+datum_customer_ele_fee.fee_compare))|2)`)}
          // &where="datum_customer_ele_fee.credit_ele_table_id".in(${d.credit_ele_table_id})&groupFields=ele_date&fields=ele_date`)
          this.$api
            .getData(
              'credit',
              'datum_customer_ele_fee',
              {
                'credit_ele_table_id.eq': d.credit_ele_table_id,
              },
              { ele_date: 'asc' }
            )
            .then(res => {
              if (res && res.data) {
                d.eleFee = res.data || []
                const xData = []
                const aData = []
                const bData = []
                for (let t of d.eleFee) {
                  xData.push(t.ele_date)
                  const fee = Number.parseFloat(t.ele_fee)
                  const nowFee = isNaN(fee) ? 0 : fee
                  aData.push(nowFee)
                  const compare = Number.parseFloat(t.fee_compare.replace(/(.*)%$/, '$1'))
                  // const lastFee = isNaN(compare) ? '-' : Math.round(nowFee * (1 + compare / 100) * 100) / 100
                  const lastFee = isNaN(compare)
                    ? '-'
                    : (Math.round(nowFee / (1 + compare / 100)) * 100) / 100
                  bData.push(lastFee)
                }

                d.option = {
                  backgroundColor: '#eff8fe',
                  title: {
                    text: '电费明细',
                    subtext: '',
                    left: 'center',
                  },
                  tooltip: {
                    trigger: 'axis',
                  },
                  legend: {
                    top: 32,
                    data: ['今年', '上年同期'],
                  },
                  xAxis: [
                    {
                      type: 'category',
                      data: xData,
                      axisLabel: {
                        formatter: v => echartsXFormatter(v, 5),
                      },
                    },
                  ],
                  yAxis: [
                    {
                      type: 'value',
                      name: '电费使用',
                    },
                  ],
                  series: [
                    {
                      name: '今年',
                      type: 'line',
                      data: aData,
                    },
                    {
                      name: '上年同期',
                      type: 'line',
                      data: bData,
                    },
                  ],
                }

                if (this.id && d.chart && d.chart.getDataURL) {
                  d.chart.on('finished', () => {
                    d.imgData = d.chart.getDataURL()
                  })
                }
              }
            })
        }
      }
    },
    gettableflData() {
      // const params = {...this.params['customer_id.eq']}
      this.$api
        .getData(
          'credit',
          'credit_visit_record',
          {
            'customer_related_id.eq': this.id,
          },
          { create_time: 'desc' }
        )
        .then(res => {
          this.tableData = res.data
        })
    },
    getRelatedData() {
      this.$api
        .getData(
          'credit',
          'customer_related_view',
          {
            'customer_related_id.eq': this.id,
          },
          { create_time: 'desc' }
        )
        .then(res => {
          this.relatedData = (res && res.data && res.data.length && res.data[0]) || {}
        })
    },
    getflowData() {
      this.$api
        .getData('credit', this.flowName, {
          'customer_related_id.eq': this.id,
        })
        .then(res => {
          if (!res.data) {
            return
          }
          this.PostEle = {}
          this.feilData = {}
          this.abaData = {}
        })
    },
    getfinanceData() {
      this.$api
        .getData('credit', 'credit_load_behind_new_view', {
          'customer_related_id.eq': this.id,
        })
        .then(res => {
          if (!res.data) {
            return
          }
          this.financeData = res.data[0]
        })
    },
    fixed() {
      this.editVisible = true
    },
    abnorma() {
      this.abaData = { visit_des: '' }
      this.abnormaVisible = true
    },
    power() {
      this.powerVisible = true
    },
    hanldClose() {
      this.editVisible = false
    },
    hanldRecordClose() {
      this.editRecordVisible = false
    },
    // 用电分析
    gopower() {
      // this.getEleDataView()
      this.powerVisible = true
    },
    powerClose() {
      this.powerVisible = false
    },
    // 监管记录
    goabnorma() {
      this.abnormaVisible = true
    },
    abnormaClose() {
      this.date = ''
      this.visit_type = ''
      this.time = ''
      this.money = ''
      this.abnormaVisible = false
    },
    // 财务
    gofinance() {
      localStorage.setItem('accountId', this.financeData.customer_id)
      this.$router.push({
        path: '/credit/task/accountlist',
        query: { id: this.financeData.customer_id },
      })
    },
    gocontrol() {
      this.controlVisible = true
    },
    controlClose() {
      this.controlVisible = false
    },
    gofarm(val) {
      // this.farmVisible = true
      window.open(
        `${window.location.protocol}//${window.location.host.replace(
          /^\\w+\\./g,
          ''
        )}/datas/farmdetail?farmId=` + val
      )
    },
    farmClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done()
        })
        .catch(() => {
          this.farmVisible = false
        })
    },
    setType() {
      this.date = ''
      this.time = ''
      this.money = ''
      this.abaData.visit_des = this.visit_type + '： '
    },
    setTime() {
      this.abaData.visit_des =
        this.visit_type +
        '： ' +
        ' 逾期时间：' +
        (this.date || '') +
        ', ' +
        ' 逾期时长: ' +
        (this.time || 0) +
        '天' +
        ', ' +
        ' 逾期金额: ' +
        (this.money || 0) +
        ' 元,'
    },
    async submitnorma(service, data, tableName) {
      data.customer_id = this.relatedData.customer_id
      data.customer_name = this.relatedData.customer_name
      data.customer_related_id = this.id
      data.visit_person = this.realName || this.name
      data.visit_date = visdate
      data.visit_type = '3'
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(this.$api.addData(service, tableName, data))
      this.saveLoading = false
      if (res) {
        this.$message.success('数据采集成功！！')
        this.gettableflData()
        this.abnormaClose()
        this.$store.dispatch('getTaskCount')
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    async updateRecord(service, data, tableName) {
      data.customer_id = this.relatedData.customer_id
      data.customer_name = this.relatedData.customer_name
      data.customer_related_id = this.id
      data.visit_person = this.realName || this.name
      // data.visit_date = visdate
      if (!data.visit_date) {
        this.$message.error('走访时间必填！')
        return
      }
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.updateData(service, tableName, this.recordId, data)
      )
      this.saveLoading = false
      if (res) {
        this.$message.success('数据修改成功！')
        this.hanldRecordClose()
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    editData(item) {
      this.recordData = item
      this.recordId = item.id
      this.editRecordVisible = true
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '完成中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.flowName, item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('保存成功！')
              this.gettableflData()
              done()
            } else {
              this.$message.error('保存失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    showAbnorma() {
      this.abEditorVisible = true
    },
    showRepayList() {
      this.repayEditorVisble = true
    },
  },
}
</script>
<style scoped>
/*.el-select-dropdown__item {*/
/*color: red;*/
/*}*/
</style>
